<template>
  <div class="page">
    <div class="custom-calendar">
      <!-- 日历头部 -->
      <div class="calendar-header">
        <span class="header-date">{{ displayDate }}</span>
        <span class="header-today" v-if="goTodayHe" @click.stop="goToday">回到今天</span>
      </div>

      <view class="top-bar">
        <u-icon class="top-bar-icon" @click="turningYear('prev')" name="arrow-left-double" size="20"></u-icon>
        <u-icon class="top-bar-icon" @click="turning('prev')" name="arrow-left" size="20"></u-icon>
        <view class="top-bar-ym">{{ textDate }}</view>
        <u-icon class="top-bar-icon" @click="turning('next')" name="arrow-right" size="20"></u-icon>
        <u-icon class="top-bar-icon" @click="turningYear('next')" name="arrow-right-double" size="20"></u-icon>
      </view>

      <!-- 日历内容区域 -->
      <div class="calendar-content" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
        @touchend="handleTouchEnd">
        <!-- 星期标题 -->
        <div class="week-row">
          <div class="week-cell" v-for="day in fullWeekDays" :key="day">{{ day }}</div>
        </div>

        <!-- 日期网格 -->
        <div class="date-grid-container" :class="{ 'expanded': isExpanded, 'collapsed': !isExpanded }">
          <div class="date-grid">
            <div class="date-cell " v-for="(date, index) in displayedDates" :key="index" :class="{
              'other-month': !date.isCurrentMonth,
              'today': date.isToday,
              'selected': date.isSelected
            }" @click="selectDate(date)">
              <div class="date-inner">{{ date.day }}</div>
              <!-- 考勤状态显示（上午+下午） -->
              <div class="attendance-wrap" v-if="date.isCurrentMonth">
                <div class="attendance-item morning" :class="getAttendanceClass(date, '上午')">
                  {{ getAttendanceText(date, '上午') }}
                </div>
                <div class="attendance-item afternoon" :class="getAttendanceClass(date, '下午')">
                  {{ getAttendanceText(date, '下午') }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 展开/收起按钮 -->
      <div class="calendar-toggle-line" @click="toggleExpand">
        <div class="line"></div>
        <div class="arrow-icon">
          <u-icon v-if="!isExpanded" color="#999" name="arrow-down" size="24"></u-icon>
          <u-icon v-else color="#999" name="arrow-up" size="24"></u-icon>
        </div>
        <div class="line"></div>
      </div>

      <!-- 考勤颜色标识说明 -->
      <div class="attendance-legend">
        <div class="legend-item" v-for="(item, key) in attendanceConfig" :key="key">
          <!-- 改为使用 item.classKey 生成 CSS 类名 -->
          <div class="legend-color" :class="`kaoqin-${item.classKey}`"></div>
          <div class="legend-text">{{ item.text }}</div>
        </div>
        <!-- 迟到/早退单独添加标识 -->
        <div class="legend-item">
          <div class="legend-color kaoqin-chidao"></div>
          <div class="legend-text">迟到/早退</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    dataList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      currentDate: new Date(),
      isExpanded: true,
      fullWeekDays: ['一', '二', '三', '四', '五', '六', '日'],
      touchStartX: 0,
      touchEndX: 0,
      positionTop: 0,

      attendanceConfig: {
        '/': { text: '出勤', classKey: 'chuqin' },
        'T': { text: '调休', classKey: 'tiaoxiu' },
        '○': { text: '事假', classKey: 'shijia' },
        '╳': { text: '旷工', classKey: 'kuanggong' },
        'G': { text: '公休', classKey: 'gongxiu' },
        '□': { text: '出差', classKey: 'chuchai' },
        'Ｎ': { text: '年假', classKey: 'nianjia' },
        'H': { text: '婚假', classKey: 'hunjia' },
        'S': { text: '丧假', classKey: 'sangjia' },
        '陪': { text: '陪产假', classKey: 'peichan' },
        '产': { text: '产假', classKey: 'chanjia' },
        '△': { text: '病假', classKey: 'bingjia' },
        '补': { text: '补卡', classKey: 'buka' },
        '-': { text: '未入职', classKey: 'weiruzhi' },
        '离': { text: '离职', classKey: 'lizhi' }
      }
    }
  },
  computed: {
    displayDate () {
      const year = this.currentDate.getFullYear()
      const month = (this.currentDate.getMonth() + 1).toString().padStart(2, '0')
      const day = this.currentDate.getDate().toString().padStart(2, '0')
      return `${year} | ${month}.${day}`
    },
    textDate () {
      const year = this.currentDate.getFullYear()
      const month = (this.currentDate.getMonth() + 1).toString().padStart(2, '0')
      return `${year} 年 ${month} 月`
    },
    // 获取当前月需要展示的所有日期（含补充的前后月份）
    visibleDates () {
      const year = this.currentDate.getFullYear()
      const month = this.currentDate.getMonth()
      const today = new Date()

      const firstDay = new Date(year, month, 1)
      const lastDay = new Date(year, month + 1, 0)
      const firstDayOfWeek = firstDay.getDay() || 7 // 处理周日为 0 的情况

      const dates = []

      // 添加上个月的部分日期填充空格
      const prevMonthDays = firstDayOfWeek - 1
      const prevMonthLastDay = new Date(year, month, 0).getDate()
      for (let i = prevMonthDays; i > 0; i--) {
        const day = prevMonthLastDay - i + 1
        dates.push({
          day,
          date: new Date(year, month - 1, day),
          isCurrentMonth: false,
          isToday: false,
          isSelected: false
        })
      }

      // 当前月日期
      for (let i = 1; i <= lastDay.getDate(); i++) {
        const date = new Date(year, month, i)
        const isToday = date.toDateString() === today.toDateString()
        const isSelected = date.toDateString() === this.currentDate.toDateString()
        dates.push({
          day: i,
          date,
          isCurrentMonth: true,
          isToday,
          isSelected
        })
      }

      // 添加下个月的日期填补 6 行 × 7 列 = 42 个格子
      const remainingCells = 42 - dates.length
      for (let i = 1; i <= remainingCells; i++) {
        dates.push({
          day: i,
          date: new Date(year, month + 1, i),
          isCurrentMonth: false,
          isToday: false,
          isSelected: false
        })
      }

      return dates
    },
    // 根据是否展开来决定展示全部日期还是一周
    displayedDates () {
      if (this.isExpanded) {
        return this.visibleDates
      } else {
        const selectedIndex = this.visibleDates.findIndex(d => d.date.toDateString() === this.currentDate.toDateString())
        if (selectedIndex === -1) return []
        const startOfWeek = Math.floor(selectedIndex / 7) * 7
        return this.visibleDates.slice(startOfWeek, startOfWeek + 7)
      }
    },
    // 判断回到今天是否显示
    goTodayHe () {
      const today = new Date()
      const current = this.currentDate
      return (
        today.getFullYear() !== current.getFullYear() ||
        today.getMonth() !== current.getMonth() ||
        today.getDate() !== current.getDate()
      )
    }
  },
  watch: {
    dataList: {
      handler (value) {

      },
      deep: true
    }
  },
  methods: {
    // 切换展开/收起状态
    toggleExpand () {
      this.isExpanded = !this.isExpanded
    },
    // 回到今天
    goToday () {
      this.currentDate = new Date()
    },
    // 选择某个日期
    selectDate (date) {
      this.currentDate = new Date(date.date)
    },
    // 上个月
    prevMonth () {
      this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() - 1, 1)
    },
    // 下个月
    nextMonth () {
      this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() + 1, 1)
    },
    // 上一年
    prevYear () {
      this.currentDate = new Date(this.currentDate.getFullYear() - 1, this.currentDate.getMonth(), 1)
    },
    // 下一年
    nextYear () {
      this.currentDate = new Date(this.currentDate.getFullYear() + 1, this.currentDate.getMonth(), 1)
    },
    // 触摸开始事件
    handleTouchStart (e) {
      this.touchStartX = e.changedTouches[0].clientX
    },
    // 阻止默认行为（如滚动）
    handleTouchMove (e) {
      e.preventDefault()
    },
    // 触摸结束，触发滑动判断
    handleTouchEnd (e) {
      this.touchEndX = e.changedTouches[0].clientX
      this.handleSwipe()
    },
    // 判断滑动方向并翻月
    handleSwipe () {
      if (!this.isExpanded) return
      const diffX = this.touchStartX - this.touchEndX
      const swipeThreshold = 50
      if (diffX > swipeThreshold) {
        this.nextMonth()
      } else if (diffX < -swipeThreshold) {
        this.prevMonth()
      }
    },
    // 上个月/下个月切换
    turning (_action) {
      _action === 'next' ? this.nextMonth() : this.prevMonth()
    },
    // 上一年/下一年切换
    turningYear (_action) {
      _action === 'next' ? this.nextYear() : this.prevYear()
    },
    // 格式化日期为 yyyy-MM-dd（与 clock_date 完全对齐）
    formatDate (date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    // 获取指定日期+时段的考勤文本
    getAttendanceText (date, timeType) {
      const targetDate = this.formatDate(date.date)
      // 精准匹配 clock_date 和 time_type
      const attendanceItem = this.dataList.find(item =>
        item.clock_date === targetDate && item.time_type === timeType
      )
      if (!attendanceItem) return ''
      // 迟到/早退显示"XX分钟"，其他显示配置文本
      return attendanceItem.kaoqin_type.match(/\d+/)
        ? `${attendanceItem.kaoqin_type}分钟`
        : this.attendanceConfig[attendanceItem.kaoqin_type]?.text || ''
    },
    // 获取指定日期+时段的考勤样式类
    getAttendanceClass (date, timeType) {
      const targetDate = this.formatDate(date.date)
      const attendanceItem = this.dataList.find(item =>
        item.clock_date === targetDate && item.time_type === timeType
      )
      if (!attendanceItem) return ''
      // 迟到/早退单独样式
      if (attendanceItem.kaoqin_type.match(/\d+/)) {
        return 'kaoqin-chidao'
      }
      // 改为使用 classKey 拼接 CSS 类名
      const config = this.attendanceConfig[attendanceItem.kaoqin_type]
      return config ? `kaoqin-${config.classKey}` : ''
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  user-select: none;

  .custom-calendar {
    width: 100%;
    background: #fff;
    border-radius: 4px;
    overflow: hidden;

    .calendar-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      position: relative;

      .header-date {
        font-size: 16px;
        font-weight: bold;
        flex-grow: 1;
        text-align: left;
      }

      .header-today {
        position: absolute;
        left: 80%;
        transform: translateX(-50%);
        font-size: 14px;
        color: #ccc;
        cursor: pointer;
        text-align: right;
      }
    }

    .top-bar {
      display: flex;
      justify-content: space-between;
      padding: 0 24upx;
      height: 80upx;
      align-items: center;

      .top-bar-icon {
        width: 30upx;
        cursor: pointer;
      }

      .top-bar-ym {
        text-align: center;
        font-size: 32upx;
        height: 80upx;
        line-height: 80upx;
      }
    }

    .calendar-content {
      padding: 8px 0;
      touch-action: pan-y;

      .week-row {
        display: flex;
        padding: 8px 0;

        .week-cell {
          flex: 1;
          text-align: center;
          font-size: 12px;
          color: #666;
        }
      }

      .date-grid {
        display: flex;
        flex-wrap: wrap;

        .date-cell {
          margin-top: 6rpx;
          flex: 0 0 14.28%;
          height: auto;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          font-size: 14px;
          cursor: pointer;
          position: relative;

          .date-inner {
            margin-top: 1px;
            width: 28px;
            height: 28px;
            line-height: 28px;
            text-align: center;
            margin-bottom: 4px;
          }

          // 考勤容器
          .attendance-wrap {
            width: 80%;
            display: flex;
            flex-direction: column;
            gap: 2px;
          }

          // 考勤项样式
          .attendance-item {
            font-size: 10px;
            padding: 2px 0;
            border-radius: 2px;
            color: #fff;
            text-align: center;
            width: 100%;
          }

          &.other-month {
            color: #ccc;
          }

          &.today .date-inner {
            color: #007aff;
            font-weight: bold;
          }

          &.selected {
            background-color: #1890ff;
            border-radius: 8px; // 圆角优化
            padding: 2px 0; // 内边距增加，让框体更饱满
          }

          &.selected .date-inner {
            color: white; // 选中日期文字白色
            background: transparent; // 取消原有圆形背景
            font-weight: 600; // 文字加粗，更醒目
          }

          &.today.selected .date-inner {
            color: white; // 覆盖今天的蓝色文字
          }
        }
      }
    }

    .calendar-toggle-line {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 8px 0;
      cursor: pointer;

      .line {
        flex: 1;
        height: 1px;
        background-color: #ccc;
        margin: 0 8px;
      }

      .arrow-icon {
        font-size: 14px;
        color: #666;
        padding: 0 4px;
      }
    }

    .attendance-statistics {
      display: flex;
      justify-content: space-between;
      padding: 12px 16px;
      background-color: #f9f9f9;
      border-top: 1px solid #eee;
      border-bottom: 1px solid #eee;

      .stat-item {
        display: flex;
        align-items: center;
        font-size: 14px;

        .stat-label {
          color: #666;
          margin-right: 4px;
        }

        .stat-value {
          color: #1890ff;
          font-weight: 600;
        }
      }
    }

    // 考勤颜色标识区域
    .attendance-legend {
      display: flex;
      flex-wrap: wrap;
      padding: 12px 5px;
      gap: 8px 13px;
      background: #f5f5f5;
      justify-content: flex-start;

      .legend-item {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
        color: #666;
        white-space: nowrap;
      }

      .legend-color {
        width: 16px;
        height: 16px;
        border-radius: 2px;
      }
    }

    // 考勤类型颜色样式
    .kaoqin-chuqin {
      background-color: #52c41a;
    }

    // 出勤-绿色
    .kaoqin-tiaoxiu {
      background-color: #1890ff;
    }

    // 调休-蓝色
    .kaoqin-shijia {
      background-color: #faad14;
    }

    // 事假-黄色
    .kaoqin-kuanggong {
      background-color: #ff4d4f;
    }

    // 旷工-红色
    .kaoqin-gongxiu {
      background-color: #91d5ff;
    }

    // 公休-浅蓝
    .kaoqin-chuchai {
      background-color: #722ed1;
    }

    // 出差-紫色
    .kaoqin-nianjia {
      background-color: #52c41a;
    }

    // 年假-绿色
    .kaoqin-hunjia {
      background-color: #ffc53d;
    }

    // 婚假-橙黄
    .kaoqin-sangjia {
      background-color: #8c8c8c;
    }

    // 丧假-灰色
    .kaoqin-peichan {
      background-color: #ff7a45;
    }

    // 陪产假-橙红
    .kaoqin-chanjia {
      background-color: #ff4d94;
    }

    // 产假-粉红
    .kaoqin-bingjia {
      background-color: #40a9ff;
    }

    // 病假-天蓝
    .kaoqin-buka {
      background-color: #a0d911;
    }

    // 补卡-亮绿
    .kaoqin-weiruzhi {
      background-color: #d9d9d9;
    }

    // 未入职-浅灰
    .kaoqin-lizhi {
      background-color: #737373;
    }

    // 离职-深灰
    .kaoqin-chidao {
      background-color: #fa8c16;
    }

    // 迟到/早退-橙色
  }
}
</style>